package com.cndw.kungfu.model.pvp.camp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicIntegerArray;

import com.cndw.kungfu.ext.NumberProcesser;

class CampWarBase {

	/**
	 * 参加比赛的人
	 */
	protected static final ConcurrentHashMap<Long, CampWarPlayer> joinPlayers = new ConcurrentHashMap<Long, CampWarPlayer>();

	protected static final ConcurrentHashMap<Integer, LinkedList<CampWarLog>> records = new ConcurrentHashMap<Integer, LinkedList<CampWarLog>>();

	protected static List<Object> topPlayers = new ArrayList<Object>();

	protected static boolean open = false;

	protected static AtomicIntegerArray joinRecord = new AtomicIntegerArray(10);

	protected static int nameIndexLeft = 0;
	protected static int nameIndexRight = 0;

	protected static ScheduledFuture<?> vsTask;

	protected final static void clearOnStart() {
		joinPlayers.clear();
		records.clear();
		topPlayers.clear();
		joinRecord = new AtomicIntegerArray(10);
		nameIndexLeft = NumberProcesser.mtRand(8) - 1;
		nameIndexRight = NumberProcesser.mtRand(8) - 1;
	}

	protected final static void clearOnEnd() {
		joinPlayers.clear();
		records.clear();
		open = false;
	}

	protected synchronized static void recordsAdd(int area, Collection<CampWarLog> logs) {
		if (!records.containsKey(area)) {
			records.putIfAbsent(area, new LinkedList<CampWarLog>());
		}
		records.get(area).addAll(logs);

		// LogUtil.getMain().debug(area+":"+records.get(area).size());
	}

	public static Collection<CampWarLog> recordsView(int area, int limit) {
		LinkedList<CampWarLog> logs = records.get(area);
		if (logs == null) {
			return null;
		}
		int size = logs.size();
		if (limit == 0 || limit >= size) {
			return new ArrayList<CampWarLog>(logs);
		}
		return new ArrayList<CampWarLog>(logs.subList(size - limit, size));
	}

	public static Collection<CampWarLog> recordsView(int area, long uid, int limit) {
		LinkedList<CampWarLog> logs = records.get(area);
		if (logs == null || logs.size() == 0) {
			return null;
		}
		ArrayList<CampWarLog> cList = new ArrayList<CampWarLog>();

		Iterator<CampWarLog> it = logs.descendingIterator();
		int i = 0;
		while (it.hasNext()) {
			CampWarLog campWarLog = (CampWarLog) it.next();
			if (campWarLog != null) {
				if (campWarLog.getWinId() != uid && campWarLog.getLossId() != uid) {
					continue;
				}
				cList.add(campWarLog);
				i++;
				if (i >= limit) {
					break;
				}
			}
		}
		return cList;
	}

	public static int getNameIndexLeft() {
		return nameIndexLeft;
	}

	public static int getNameIndexRight() {
		return nameIndexRight;
	}

	public static Object getTop3() {
		return topPlayers;
	}

}
